package com.wilmer.aliyun.utils;

import com.alibaba.fastjson2.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.wilmer.aliyun.config.AliyunSSMConfig;
import com.wilmer.common.exception.base.BaseException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author hans
 *  @date 2024-03-7
 * @msg 阿里云发送短信组件
 */
@Component
public class AliyunSSMUtils {

    @Resource
    private AliyunSSMConfig aliyunSSMConfig;

    public boolean sendMessage(String phone, String code) {
        DefaultProfile profile = DefaultProfile.getProfile(aliyunSSMConfig.getRegionId(), aliyunSSMConfig.getAccessKeyId(), aliyunSSMConfig.getSecret());
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(aliyunSSMConfig.getDomain());
        request.setSysVersion(aliyunSSMConfig.getVersion());
        request.setSysAction(aliyunSSMConfig.getAction());
        request.putQueryParameter("RegionId", aliyunSSMConfig.getRegionId());
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", aliyunSSMConfig.getSignName());
        request.putQueryParameter("TemplateCode", aliyunSSMConfig.getTemplateCode());
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            String status = JSONObject.parseObject(response.getData()).get("Code").toString();
            if(status.equals("isv.MOBILE_NUMBER_ILLEGAL")){
                throw new BaseException("手机号格式不正确！");
            }
            if(status.equals("isv.BUSINESS_LIMIT_CONTROL")){
                throw new BaseException("操作过于频发，请稍后再试！");
            }
            return "OK".equals(status);
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }
}
